<template>
  <a-modal :title="'添加部位'" :visible="true" width="60%" :footer="null" @cancel="reset">
    <div class="main">
      <a-card>
        <div class="steps-content">
          <a-row type="flex" justify="start" align="top">
            <a-col :span="24">
              <a-form :form="form" :labelCol="formItemLayout.labelCol" :wrapperCol="formItemLayout.wrapperCol">
                <a-form-item label="部位">
                  <a-select allow-clear :required="true" show-search placeholder="请选择部位" @change="changePart" v-decorator="[
                    'partId',
                    {
                      rules: [{ required: true, message: '请选择部位!' }]
                    }
                  ]">
                    <a-select-option :value="item.name" v-for="(item, index) in partList" :key="index">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item label="做法">
                  <a-select allow-clear show-search @change="changeOper" placeholder="请选择做法" v-decorator="[
                    'operId',

                  ]">
                    <a-select-option :value="item.name" v-for="(item, index) in operList" :key="index">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item label="序号">
                  <a-input allow-clear placeholder="请输入序号" :rows="4" :maxLength="500" v-decorator="[
                    'seq',
                  ]"></a-input>
                </a-form-item>
                <a-form-item label="图片" help="只支持图片格式" style="text-align:left" :required="true">
                  <!-- <JImageUpload style="display:flex;flex-wrap: wrap;width:100%" :fileSize="5"
                    :uploadParams="getUploadParams()" :accept="'image/*'" @fileChange="fileXcxImageChange"
                    v-model="fileList"></JImageUpload> -->
                  <a-upload name="file" list-type="picture-card" :multiple="true" class="avatar-uploader"
                    :data="{ type: 1 }" :fileList="fileList" @change="handleChange" :action="uploadUrl">
                    <div>
                      <a-icon type="plus" />
                      <div class="ant-upload-text">
                        上传图片
                      </div>
                    </div>
                  </a-upload>
                </a-form-item>
                <a-form-item label="描述" :required="true">
                  <a-textarea allow-clear placeholder="请输入描述" :rows="4" :maxLength="500" v-decorator="[
                    'description',
                    {
                      rules: [{ required: true, message: '请输入描述!' }]
                    }
                  ]"></a-textarea>

                </a-form-item>
              </a-form>
            </a-col>
          </a-row>
        </div>
        <div class="steps-action">
          <div>
            <a-button :loading="loading" type="primary" style="margin-left: 8px" @click="toSubmit">
              提交
            </a-button>
          </div>
        </div>
      </a-card>
    </div>
  </a-modal>
</template>

<script>
import { getDictChildList } from '@api/rd/index'
import { savePart, updatePart } from '@api/rd/index'
import globalData from '@/assets/js/common'
import { uploadUrl } from '@api/rd/index.js'
import JImageUpload from '@/components/qiniuUpload/JImageUpload.vue'
export default {
  components: { JImageUpload },

  props: {
    billId: {
      type: String,
      default: null
    },
    maxSeq: {
      type: Number,
      default: null
    },
    partDetail: {
      type: Object,
      default: null
    }
  },

  data() {
    return {
      id: '',
      visible: false,
      loading: false,
      partList: [],
      uploadUrl,
      operList: [],
      fileList: [],
      firstForm: {},
      partId: '',
      operId: '',
      operName: '',
      partName: '',
      imageUrl: '',
      ifEdit: false,
      form: this.$form.createForm(this),
      formItemLayout: {
        labelCol: {
          xl: { span: 5 }
        },
        wrapperCol: {
          xl: { span: 15 }
        }
      }
    }
  },
  created() {
    this.formTile = '新增'
    this.getPartList()
    this.getOperList()
    console.log(this.partDetail);
    if (this.partDetail.id) {
      this.ifEdit = true
      this.formTile = '编辑'
      this.$nextTick(() => {
        this.form.setFieldsValue({
          seq: this.partDetail.seq,
          description: this.partDetail.description,
        })
      })
      this.partId = this.partDetail.partId
      this.operId = this.partDetail.operId
      this.partName = this.partDetail.partName
      this.operName = this.partDetail.operName
      if (this.partDetail.imgurl) {
        const obj = {
          name: 'pic.png',
          uid: this.partDetail.imgurl,
          status: 'done',
          url: this.partDetail.imgurl
        }
        this.fileList.push(obj)
      }
      this.imgurl = this.partDetail.imgurl
    }

  },
  computed: {
    userInfo() {
      return this.$store.getters.userInfo || null
    }
  },
  methods: {
    reset() {
      this.form.resetFields()
      this.$emit('closeAddPart')
    },
    changePart(value) {
      this.partList.map(item => {
        if (item.name == value) {
          this.partId = item.code
        }
      })
      this.partName = value
    },
    changeOper(value) {
      this.operList.map(item => {
        if (item.name == value) {
          this.operId = item.code
        }
      })
      this.operName = value
    },
    // 上传图片
    getUploadParams() {
      return { ...globalData.uploadParams }
    },
    fileXcxImageChange(list) {
      this.imgurl = list[0].url
    },
    handleChange(info, item, index) {
      let fileList = [...info.fileList]
      this.fileList = [...fileList]
      if (info.file.status === 'uploading') {
        return
      }
      if (info.file.status === 'done') {
        let list = fileList.map(file => {
          if (file.response) {
            file.url = file.response.data.url
          }
          return file
        })
        this.fileList = list.slice(-1)
      }
      if (info.file.response.code != '200') {
        this.$message.error(info.file.response.msg)
        info.file.status = 'error'
        this.fileList.map((item) => {
          if (item.thumbUrl == info.file.thumbUrl) {
            item.status = 'error'
          }
        })
      }
    },
    async getPartList() {
      const params = {
        name: 'GY_PART'
      }
      try {
        const res = await getDictChildList('dict', params)
        if (res.code == 200) {
          this.partList = res.data
          if (this.partDetail.partName) {
            this.form.setFieldsValue({
              partId: this.partDetail.partName,
            })
          }
        } else {
          if (res.msg) {
            this.$message.error(res.msg)
          } else {
            this.$message.error('获取部位列表失败！')
          }
        }
      } catch (error) {
        this.$message.error('获取部位列表失败！')
      }
    },
    async getOperList() {
      const params = {
        name: 'GY_OPER'
      }
      try {
        const res = await getDictChildList('dict', params)
        if (res.code == 200) {
          this.operList = res.data
          if (this.partDetail.id) {
            this.form.setFieldsValue({
              operId: this.partDetail.operName
            })
          }
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        this.$message.error('获取做法列表失败！')
      }
    },
    toSubmit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.firstForm = values
          this.submit()
        }
      })
    },
    async submit() {
      console.log(this.fileList);
      this.imgurl = this.fileList[0].url
      this.loading = true
      if (!this.imgurl) {
        this.$message.error('上传图片！')
      } else {
        const params = {
          imgurl: this.imgurl,
          operId: this.operId,
          operName: this.operName,
          partId: this.partId,
          partName: this.partName,
          seq: this.firstForm.seq || this.firstForm.seq == 0 ? this.firstForm.seq : this.maxSeq + 1,
          billId: this.billId,
          subSeq: 0,
          description: this.firstForm.description
        }
        if (this.ifEdit) {
          params.id = this.partDetail.id
        }
        const { realname } = this.userInfo
        params.operator = realname
        var paramsArr = []
        paramsArr.push(params)
        try {
          const res = this.ifEdit ? await updatePart('bill', params) : await savePart('bill', paramsArr)
          if (res.code == 200) {
            this.$message.success(this.ifEdit ? '编辑部位信息成功！' : '添加部位信息成功！')
            this.reset()
          } else {
            this.$message.warning(res.msg)
          }
        } catch (error) {
          this.$message.warning('操作失败！')
        } finally {
          this.loading = false
        }
      }
    }
  }
}
</script>

<style scoped lang="less">
.info-action {
  display: flex;
  flex-direction: row;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: flex-end;
  // margin-bottom: 20px;
}

.ml-20 {
  margin-left: 20px;
}

.steps-content {
  margin-top: 16px;
  min-height: 200px;
  text-align: center;
  padding-top: 20px;
}

.steps-action {
  display: flex;
  justify-content: flex-end;
  margin-top: 24px;
}
</style>
